package pers.kw.config.oauth;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import pers.kw.protocol.ExceptionResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private static final Logger log = LoggerFactory.getLogger(MyAuthenticationEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.error("客户端信息异常处理：", authException);
        String msg = authException.getMessage();
        if (authException instanceof BadCredentialsException) {
            msg = "客户端凭据信息错误";
        }
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType(ContentType.build(ContentType.JSON.getValue(), Charset.defaultCharset()));
        response.setStatus(HttpStatus.HTTP_BAD_REQUEST);
        response.getWriter().write(mapper.writeValueAsString(
                ExceptionResponse.fail(HttpStatus.HTTP_BAD_REQUEST, msg)
        ));
    }
}
